﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using YiDa.Repository.EntityFramework.Test.Modal;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using YiDa.Infrastructure;
using YiDa.Domain.Repositories;
using YiDa.Domain.Specifications;
using Microsoft.CSharp;
namespace YiDa.Repository.EntityFramework.Test
{
    [TestClass]
    public class UnitTest
    {
        [TestMethod]
        public void TestFindObjects()
        {
            var re = ServiceLocator.Instance.GetService<IRepository<School>>();

            var list = re.FindAll(Specification<School>.Eval(s => s.Name.Contains("中学")), s => s.Name, SortOrder.Descending);
            Assert.AreEqual(2, list.Count());
        }

        [TestMethod]
        public void TestEagerLoading()
        {
            //使用Repository
            var re = ServiceLocator.Instance.GetService<IRepository<School>>();
            var list = re.FindAll(Specification<School>.Eval(s => s.Name.Contains("中学")), s => s.Name, SortOrder.Descending, s => s.SchoolClasses[0].Students, s => s.SchoolClasses[0].Students);
            Assert.AreEqual(2, list.Count());

            //var c = (EFTestDbContext)((IEntityFrameworkRepositoryContext)re.Context).Context;
            //直接用EF的方式-1            
            //var result = c.Schools.Include(t => t.SchoolClasses.Select(sc => sc.Students)).ToList();
            
            //使用path字符串方法1
            //var result = c.Schools.Include("SchoolClasses.Students").ToList();

            //Assert.AreEqual(2, result.Count);
        }

        [TestMethod]
        public void TestJoin()
        {
            //var re = ServiceLocator.Instance.GetService<IRepository<School>>();

            //var c = (EFTestDbContext)((IEntityFrameworkRepositoryContext)re.Context).Context;

            //var list = from school in c.Schools join sc in c.SchoolClasses on school equals sc.School orderby school.Name,sc.Name select new { SchollName = school.Name,ClassName=sc.Name };
            //var result = list.ToList();
            //Assert.AreEqual(4, result.Count());

            var result = getJoinResult();
            var o = result[0].SchollName;
            Assert.IsNotNull(o);
        }

        //dynamic
        public List<dynamic> getJoinResult()
        {
            var re = ServiceLocator.Instance.GetService<IRepository<School>>();

            var c = (EFTestDbContext)((IEntityFrameworkRepositoryContext)re.Context).Context;

            var list = from school in c.Schools join sc in c.SchoolClasses on school equals sc.School orderby school.Name, sc.Name select new { SchollName = school.Name, ClassName = sc.Name };
            return new List<dynamic>(list.ToArray());
        }
    }
}
